#include "stdafx.h"
#include "./glApp.h"

#include "./glTrace.h"

namespace GLES
{
	GLContext context;

	Bool CreateGLContext(HWND hwnd)
	{
		EGLint		aEGLAttributes[] = {
			EGL_RED_SIZE, 8,
			EGL_GREEN_SIZE, 8,
			EGL_BLUE_SIZE, 8,
			EGL_ALPHA_SIZE,8,
			EGL_DEPTH_SIZE, 16,
			EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT,
			EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
			EGL_BIND_TO_TEXTURE_RGBA, EGL_TRUE,

			EGL_NONE
		};

		EGLint		aEGLContextAttributes[] = {
			EGL_CONTEXT_CLIENT_VERSION, 1,
			EGL_NONE
		};

		context.m_hwnd = hwnd;

		EGLint	   Width;
		EGLint	   Height;
		EGLint	   major = 0;
		EGLint	   minor = 0;

		EGLint nConfigs;
		
		do 
		{
			E_Break_If((context.m_eglDisplay = eglGetDisplay(GetDC(hwnd))) == 0);

			E_Break_If(!eglInitialize(context.m_eglDisplay, &major, &minor));

			xInfor2("OpenGL ES version %d.%d",major,minor);

			E_Break_If(!eglChooseConfig(context.m_eglDisplay, aEGLAttributes, context.m_eglConfig, 1, &nConfigs));

			E_Break_If((context.m_eglContext = eglCreateContext(context.m_eglDisplay, context.m_eglConfig[0], EGL_NO_CONTEXT, aEGLContextAttributes)) == EGL_NO_CONTEXT);

			return true;
		} while (0);
		return false;
	};

	Bool DeleteGLContext()
	{
		// Exit.
		do 
		{
			eglMakeCurrent(context.m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
			eglDestroyContext(context.m_eglDisplay, context.m_eglContext);
			eglTerminate(context.m_eglDisplay);
			return true;
		} while (0);
		return false;;
	};
	GLContext* getContext()
	{
		return &context;
	}
	EGLSurface CreateRenderSurface(GLint w,GLint h,GLuint Format_)
	{
		EGLint list[]=
		{
			// Specify the size of the surface.
			EGL_WIDTH, w,
			EGL_HEIGHT, h,

			EGL_RED_SIZE, 8,
			EGL_GREEN_SIZE, 8,
			EGL_BLUE_SIZE, 8,
			EGL_ALPHA_SIZE,8,
			// Target for the texture to store in the pbuffer.
			EGL_TEXTURE_TARGET, EGL_TEXTURE_2D,
			EGL_LARGEST_PBUFFER, EGL_TRUE,  
			EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
			// The format of the texture that will be created when the pBuffer is bound to a texture.
			EGL_TEXTURE_FORMAT, EGL_TEXTURE_RGBA,

			// Signal the end.
			EGL_NONE
		};
		
		EGLSurface surf;
		do 
		{
			E_Break_If((surf = eglCreatePbufferSurface(context.m_eglDisplay, context.m_eglConfig[0], list)) == EGL_NO_SURFACE);
			return surf;

		} while (0);

		return EGL_NO_SURFACE;
	}

	GLES::Void DestroyRenderSurface(EGLSurface surf)
	{
		eglDestroySurface(context.m_eglDisplay, surf);
	}

	GLES::Bool BindTexImage( EGLSurface surf )
	{
		Return(eglBindTexImage(context.m_eglDisplay, surf, EGL_BACK_BUFFER));
	}

	GLES::Bool ReleaseTexImage( EGLSurface surf )
	{
		Return(eglReleaseTexImage(context.m_eglDisplay, surf,EGL_BACK_BUFFER));
	}

}

